package com.sam.im.heiqun.uis.activities;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;


import com.sam.im.heiqun.R;
import com.sam.im.heiqun.constant.Constant;
import com.sam.im.heiqun.entities.ImMessage;
import com.sam.im.heiqun.entities.PathEntivity;
import com.sam.im.heiqun.entities.UserEntivity;
import com.sam.im.heiqun.entities.ValidateEntivity;
import com.sam.im.heiqun.entities.VedioEntity;
import com.sam.im.heiqun.entities.beans.CollectInfo;
import com.sam.im.heiqun.entities.beans.DownloadInfo;
import com.sam.im.heiqun.nets.PGService;
import com.sam.im.heiqun.uis.MediaUtil;
import com.sam.im.heiqun.uis.adapters.ChatRecyclerAdapter;
import com.sam.im.heiqun.uis.dialogs.ItemSelectorDialog;
import com.sam.im.heiqun.uis.widgets.MyPlayer;
import com.sam.im.heiqun.utils.FileUtil;
import com.sam.im.heiqun.utils.JsonUtil;
import com.sam.im.heiqun.utils.PathUtil;
import com.sam.im.heiqun.utils.RxJavaUtil;
import com.sam.im.heiqun.utils.StringUtils;
import com.sam.im.heiqun.utils.ToolsUtils;
import com.shuyu.gsyvideoplayer.GSYBaseActivityDetail;
import com.shuyu.gsyvideoplayer.GSYVideoManager;
import com.shuyu.gsyvideoplayer.builder.GSYVideoOptionBuilder;
import com.shuyu.gsyvideoplayer.utils.OrientationUtils;
import com.shuyu.gsyvideoplayer.video.StandardGSYVideoPlayer;
import com.yuyh.library.nets.callbacks.AbsAPICallback;
import com.yuyh.library.nets.exceptions.ApiException;
import com.yuyh.library.uis.activitys.BaseActivity;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

public class Play2Activity extends BaseActivity {

    MyPlayer detailPlayer;
    protected String videoUrl = "";

    private VedioEntity vedioEntity;
     private CollectInfo collectInfo;

    public static Intent newIntent(Context context, String videoUrl, VedioEntity vedioEntity, CollectInfo collectInfo) {
        Intent intent = new Intent(context, Play2Activity.class);
        intent.putExtra("videoUrl", videoUrl);
        intent.putExtra("vedioEntity", vedioEntity);
        intent.putExtra("collectInfo", collectInfo);
        return intent;
    }

    @Override
    public int getContentViewId() {
        return R.layout.activity_play2;
    }

    @Override
    public void init(Bundle savedInstanceState) {
        if (getIntent() != null && getIntent().getStringExtra("videoUrl") != null && !getIntent().getStringExtra("videoUrl").equals("")) {
            videoUrl = getIntent().getStringExtra("videoUrl");
        }
        vedioEntity = getIntent().getParcelableExtra("vedioEntity");
        collectInfo = getIntent().getParcelableExtra("collectInfo");
        // detailPlayer = (StandardGSYVideoPlayer) findViewById(R.id.detail_player);
        //增加title
        // detailPlayer.getTitleTextView().setVisibility(View.GONE);
        // detailPlayer.getBackButton().setVisibility(View.GONE);

        //    initVideoBuilderMode();
        init();
    }



    MyPlayer videoPlayer;

    OrientationUtils orientationUtils;



    private void init() {
        videoPlayer =  (MyPlayer)findViewById(R.id.video_player);
       // initLongclick();
      //  String source1 = "http://9890.vod.myqcloud.com/9890_4e292f9a3dd011e6b4078980237cc3d3.f20.mp4";
         videoPlayer.setUp(videoUrl, true, "");

        //增加封面
          ImageView imageView = new ImageView(this);
        imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
   //    imageView.setImageResource(R.mipmap.ic_launcher);
        videoPlayer.setThumbImageView(imageView);
        //增加title
        videoPlayer.getTitleTextView().setVisibility(View.VISIBLE);
        //设置返回键
        videoPlayer.getBackButton().setVisibility(View.VISIBLE);
        //设置旋转
        orientationUtils = new OrientationUtils(this, videoPlayer);
        //设置全屏按键功能,这是使用的是选择屏幕，而不是全屏
        videoPlayer.getFullscreenButton().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                orientationUtils.resolveByClick();
            }
        });
        //是否可以滑动调整
        videoPlayer.setIsTouchWiget(true);
        //设置返回按键功能
        videoPlayer.getBackButton().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
      //  videoPlayer.getBackButton().setImageDrawable(getResources().getDrawable(R.drawable.ic_delete));


        videoPlayer.startPlayLogic();
        videoPlayer.setmLongTouche(new MyPlayer.onLongTouchListener() {
            @Override

            public void onLongTouch() {
                Log.d("huangrui","执行长按" );
                initLongclick();
            }
        });

    }

    void initLongclick(){


                if (vedioEntity != null && !vedioEntity.isCanForward()) {
                    return ;
                }
                ItemSelectorDialog<ItemSelectorDialog.Entity> dialog = new ItemSelectorDialog<>(Play2Activity.this);
                dialog.setTitle(null);
                List<ItemSelectorDialog.Entity> itemTextList = new ArrayList<>();
                itemTextList.add(new ItemSelectorDialog.Entity(getApplicationContext().getResources().getString(com.sam.im.heiqun.R.string.send_to_friends)));
                itemTextList.add(new ItemSelectorDialog.Entity(getApplicationContext().getResources().getString(com.sam.im.heiqun.R.string.baocunshipin)));
                if (collectInfo != null) {
                    itemTextList.add(new ItemSelectorDialog.Entity(getApplicationContext().getResources().getString(com.sam.im.heiqun.R.string.collection)));
                }
                ItemSelectorDialog.Entity[] items = new ItemSelectorDialog.Entity[itemTextList.size()];
                itemTextList.toArray(items);
                dialog.setItems(items);
                dialog.setDialogClickListener(new ItemSelectorDialog.DialogItemClickListener<ItemSelectorDialog.Entity>() {
                    @Override
                    public void confirm(int position, ItemSelectorDialog.Entity result) {
                        if (getResources().getString(com.sam.im.heiqun.R.string.send_to_friends).equals(result.getText())) {

                            UserEntivity userEntivity = ToolsUtils.getUser();

                            final ImMessage imMessage = ToolsUtils.getTbub(Constant.VERSION_MESSAGE_CHART, Constant.DEV_TYPE, 0, ChatRecyclerAdapter.TO_USER_VEDIO, UUID.randomUUID().toString(),
                                    Long.parseLong(ToolsUtils.getMyUserId()), Constant.FROM_TYPE_MAM, 0, JsonUtil.toJson(vedioEntity), Constant.MESSAGE_TYPR_VEDIO,
                                    System.currentTimeMillis(), System.currentTimeMillis(), 0, JsonUtil.toJson(new PathEntivity(vedioEntity.getVedioPath(), vedioEntity.getGetVedioBitmapUrl())), ToolsUtils.getMyUserId() + "_" + "", 0, userEntivity.getHeadUrl());

                            Bundle bundle = new Bundle();
                            bundle.putSerializable("msg", imMessage);
                            bundle.putInt("tag", 11);

                            Intent intent = new Intent(Play2Activity.this, SelecteLocalFriendActivity.class);
                            intent.putExtras(bundle);
                            startActivity(intent);
                        } else if (getResources().getString(com.sam.im.heiqun.R.string.baocunshipin).equals(result.getText())) {

                            if (videoUrl == null) {
                                return;
                            }
                            File file = new File(videoUrl);
                            if (file.exists()) {
                                String fileName = StringUtils.makeFileName(videoUrl);
                                if (TextUtils.isEmpty(fileName)) {
                                    showToast(getResources().getString(com.sam.im.heiqun.R.string.save_fail));
                                    return;
                                }
                                final File saveFile = new File(PathUtil.getVideoDir(), fileName);
                                try {
                                    FileUtil.copyFile(file, saveFile);
                                } catch (IOException e) {
                                    e.printStackTrace();
                                    showToast(getResources().getString(com.sam.im.heiqun.R.string.save_fail));
                                }
                                showToast(getResources().getString(com.sam.im.heiqun.R.string.save_success) + ":" + saveFile.getAbsolutePath());
                                MediaUtil.refreshMediaFileStore(Play2Activity.this, saveFile.getAbsolutePath(), null);
                                return;
                            }
                            String fileName = StringUtils.makeFileName(vedioEntity.getVedioUrl());
                            if (TextUtils.isEmpty(fileName)) {
                                showToast(getResources().getString(com.sam.im.heiqun.R.string.save_fail));
                                return;
                            }
                            final File saveFile = new File(PathUtil.getVideoDir(), fileName);
                            RxJavaUtil.download(vedioEntity.getVedioUrl(), saveFile).compose(RxJavaUtil.<DownloadInfo>applySchedules())
                                    .compose(Play2Activity.this.<DownloadInfo>bindLifeCycle())
                                    .compose(Play2Activity.this.<DownloadInfo>applyProgress(getResources().getString(com.sam.im.heiqun.R.string.saving)))
                                    .subscribe(new AbsAPICallback<DownloadInfo>() {
                                        @Override
                                        public void onNext(DownloadInfo downloadInfo) {
                                            if (downloadInfo.isFinish()) {
                                                showToast(getResources().getString(com.sam.im.heiqun.R.string.save_success) + ":" + saveFile.getAbsolutePath());
                                                MediaUtil.refreshMediaFileStore(Play2Activity.this, saveFile.getAbsolutePath(), null);
                                            }
                                        }

                                        @Override
                                        protected void onResultError(ApiException ex) {
                                            showToast(getResources().getString(com.sam.im.heiqun.R.string.save_fail));
                                        }
                                    });
                        } else if (getResources().getString(com.sam.im.heiqun.R.string.collection).equals(result.getText())) {

                            PGService.getInstance().addcolaction(collectInfo.getCategory(),
                                    collectInfo.getUrl(),
                                    collectInfo.getContent(),
                                    collectInfo.getFromname(),
                                    ToolsUtils.getMyUserId(),
                                    collectInfo.getFromid())
                                    .compose(Play2Activity.this.<ValidateEntivity>applyProgress(null))
                                    .subscribe(new AbsAPICallback<ValidateEntivity>() {
                                        @Override
                                        protected void onResultError(ApiException ex) {
                                            if (ex != null) {
                                                String displayMessage = ex.getDisplayMessage();
                                                try {
                                                    JSONObject object = new JSONObject(displayMessage);
                                                    JSONObject data = object.getJSONObject("data");
                                                    String info = data.getString("info");
                                                    ToolsUtils.showToast(Play2Activity.this, info);
                                                } catch (JSONException e) {
                                                    e.printStackTrace();
                                                }
                                            }
                                        }

                                        @Override
                                        public void onNext(ValidateEntivity validateEntivity) {
                                            if (validateEntivity != null) {
                                                ToolsUtils.showToast(Play2Activity.this, validateEntivity.getInfo());
                                            }
                                        }
                                    });
                        }
                    }
                });
                dialog.show();

     }


    @Override
    protected void onPause() {
        super.onPause();
        videoPlayer.onVideoPause();
    }

    @Override
    protected void onResume() {
        super.onResume();
        videoPlayer.onVideoResume();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        GSYVideoManager.releaseAllVideos();
        if (orientationUtils != null)
            orientationUtils.releaseListener();
    }



    @Override
    public void onBackPressed() {
        //先返回正常状态
        if (orientationUtils.getScreenType() == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
            videoPlayer.getFullscreenButton().performClick();
            return;
        }
        //释放所有
        videoPlayer.setVideoAllCallBack(null);
        super.onBackPressed();
    }

/*    @Override
    public StandardGSYVideoPlayer getGSYVideoPlayer() {
        return detailPlayer;
    }

    @Override
    public GSYVideoOptionBuilder getGSYVideoOptionBuilder() {
        //内置封面可参考SampleCoverVideo
        ImageView imageView = new ImageView(this);
        loadCover(imageView, videoUrl);
        return new GSYVideoOptionBuilder()
                .setThumbImageView(imageView)
                .setUrl(videoUrl)
                .setCacheWithPlay(true)
                .setVideoTitle(" ")
                .setIsTouchWiget(true)
                .setRotateViewAuto(false)
                .setLockLand(false)
                .setShowFullAnimation(false)
                .setNeedLockFull(true)
                .setSeekRatio(1);
    }

    @Override
    public void clickForFullScreen() {

    }


    *//**
     * 是否启动旋转横屏，true表示启动
     *//*
    @Override
    public boolean getDetailOrientationRotateAuto() {
        return true;
    }

    private void loadCover(ImageView imageView, String url) {
        imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
      //  imageView.setImageResource(R.mipmap.xxx1);
        *//*Glide.with(this.getApplicationContext())
                .setDefaultRequestOptions(
                        new RequestOptions()
                                .frame(3000000)
                                .centerCrop()
                                .error(R.mipmap.xxx2)
                                .placeholder(R.mipmap.xxx1))
                .load(url)
                .into(imageView);*//*
    }*/

}
